package com.zzk.audiovideodemo.mediarecorder

import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.LogUtils
import com.zzk.audiovideodemo.R
import kotlinx.android.synthetic.main.activity_media_player.*


/**
 *  @author li.zhipeng
 *
 *          MediaPlayer播放视频
 * */
class MediaPlayerActivity : AppCompatActivity(), SurfaceHolder.Callback {

    companion object {

        fun open(context: Context, filePath: String) {
            val intent = Intent(context, MediaPlayerActivity::class.java)
            intent.putExtra("filePath", filePath)
            context.startActivity(intent)
        }

    }

    // 创建要保存的录音文件的路径
    private lateinit var videoRecorderFile: String

    private var mediaPlayer: MediaPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_player)
        videoRecorderFile = intent.getStringExtra("filePath")!!
        createMediaPlayer()
    }

    private fun createMediaPlayer() {
        // 把输送给surfaceView的视频画面，直接显示到屏幕上,不要维持它自身的缓冲区
        surface_view?.holder?.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS)
        // 设置播放时打开屏幕
        surface_view?.holder?.setKeepScreenOn(true)
        surface_view?.holder?.addCallback(this)
        try {
            mediaPlayer = MediaPlayer()
            //给MediaPlayer设置播放源
            mediaPlayer?.setDataSource(videoRecorderFile)
            mediaPlayer?.setOnPreparedListener {
                mediaPlayer?.start()//缓冲完，播放
            }
            mediaPlayer?.setOnCompletionListener {
                Toast.makeText(this, "播放完毕", Toast.LENGTH_SHORT).show()
                if (mediaPlayer != null) {
                    //重置mediaplayer等待下一次播放
                    mediaPlayer?.release()
                }
            }
        } catch (e: Exception) {
            Log.e("Test", "出错了", e)
        }
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        LogUtils.i("SurfaceVideoActivity->surfaceCreated")
        mediaPlayer?.setDisplay(holder)//设置播放的容器
        mediaPlayer?.prepareAsync()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        LogUtils.i("SurfaceVideoActivity->surfaceChanged")
    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        LogUtils.i("SurfaceVideoActivity->surfaceDestroyed")
        if (mediaPlayer != null && mediaPlayer?.isPlaying == true) {
            mediaPlayer?.stop()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer?.release()
        mediaPlayer = null
    }

}
